package com.example.demo.server.common;

import com.example.demo.ds.MyHashMap;
import com.example.demo.server.model.UserInfo;


public class ObjectMapper {

    public static String userinfoToJason(UserInfo userInfo) {
        StringBuilder builder = new StringBuilder();
        builder.append("{");
        builder.append("\"id\":" + userInfo.getId() + ",");
        builder.append("\"username\":\"" + userInfo.getUsername() + "\",");
        builder.append("\"name\":\"" + userInfo.getName() + "\"");
        builder.append("}");
        return builder.toString();
    }

    public static UserInfo jsonToUserinfo(String json) {
        json = json.replaceAll("\\{|\\}", "");
        String[] portions = json.split(",");
        MyHashMap<String, String> myHashMap = new MyHashMap<>();
        for (int i = 0; i < portions.length; i++) {
            String[] smallPortions = portions[i].split(":", 2);
            smallPortions[0] = smallPortions[0].substring(1, smallPortions[0].length() - 1);
            if(smallPortions[1].charAt(0) == '"' && smallPortions[1].charAt(smallPortions[1].length() - 1) =='"') {
                smallPortions[1] = smallPortions[1].substring(1, smallPortions[1].length() - 1);
            }
            myHashMap.put(smallPortions[0], smallPortions[1]);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(Integer.parseInt(myHashMap.get("id")));
        userInfo.setName(myHashMap.get("name"));
        userInfo.setUsername(myHashMap.get("username"));
        return userInfo;
    }

    public static String mapToJson(MyHashMap<String, Object> map) {
        return "{\"" + APPVariable.SESSION_KEY + "\":" + userinfoToJason((UserInfo) map.get(APPVariable.SESSION_KEY)) + "}";
    }

    public static MyHashMap<String, Object> jsonToMap(String json) {
        json = json.replaceAll("\\{|\\}", "");
        String[] portions = json.split(":", 2);
        portions[0] = portions[0].substring(1, portions[0].length() - 1);
        MyHashMap<String, Object> map = new MyHashMap<>();
        map.put(portions[0], jsonToUserinfo(portions[1]));
        return map;
    }

}
